/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.service.impl;

import com.huawei.housekeeper.model.AdminContext;
import com.huawei.housekeeper.model.ListAdminContext;
import com.huawei.housekeeper.constants.CommonConstants;
import com.huawei.housekeeper.utils.JwtTokenUtil;
import com.huawei.housekeeper.controller.request.AdminLoginDto;
import com.huawei.housekeeper.service.AdminContextService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员业务层
 *
 * @author lWX1128557
 * @since 2022-03-03
 */
@Service
public class AdminContextServiceImpl implements AdminContextService {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private ListAdminContext adminContext;

    /**
     * 管理员登录验证
     *
     * @param adminLoginDto 管理员登录Dto
     * @return token
     */
    @Override
    public String adminLogin(AdminLoginDto adminLoginDto) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(adminLoginDto.getName(), adminLoginDto.getPassword());

        // security登录内存认证
        authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        // 都验证通过即返回token
        return generateToken(adminLoginDto);
    }

    /**
     * 创建管理员token
     *
     * @return token
     */
    private String generateToken(AdminLoginDto adminLoginDto) {
        List<AdminContext> adminContextList = this.adminContext.getAdminContext();
        Map<String, Object> claims = new HashMap<>();
        adminContextList.forEach(s -> {
            if (s.getName().equalsIgnoreCase(adminLoginDto.getName())) {
                claims.put(CommonConstants.User.USER_NAME, s.getName());
                claims.put(CommonConstants.User.ROLE, s.getRole());
            }
        });
        return jwtTokenUtil.generateToken(claims);
    }
}
